package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService{
    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Menu> findAll(Integer id) {
        return roleDao.findAll(id);
    }

    @Override
    public Integer[] findMenuIdsByRoleId(Integer id) {
        return roleDao.findMenuIdsByRoleId(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Role> roles = roleDao.pageQuery(queryPageBean.getQueryString());
        return new PageResult(roles.getTotal(),roles.getResult());
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public void edit(Role role, Integer[] menuIds) {
        roleDao.edit(role);
        roleDao.deleteAssociationByRoleId(role.getId());
        this.setRoleAndMenu(role.getId(),menuIds);
    }
    public void setRoleAndMenu(Integer roleId,Integer[] menuIds){
        if(menuIds!=null || menuIds.length>0){
            Map<String,Integer> map = new HashMap<>();
            for (Integer menuId : menuIds) {
                map.put("roleId",roleId);
                map.put("menuId",menuId);
                roleDao.setUserAndRole(map);
            }
        }
    }
}
